package com.ym.core.shiro.realm;

import cn.hutool.extra.spring.SpringUtil;
import com.ym.common.constant.UserDetails;
import com.ym.core.shiro.service.UserAccLoginService;
import com.ym.core.shiro.token.UserAccToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;


/**
 * 用户账号登录
 */
@Slf4j
public class UserAccPwdShiroRealm extends AuthorizingRealm {


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		return new SimpleAuthorizationInfo();
	}

	/**
	 * 主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。
	 */

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException {
		SimpleAuthenticationInfo authenticationInfo = null;
		UserAccToken userAccToken = (UserAccToken) token;
		UserDetails userDetails = SpringUtil.getBean(UserAccLoginService.class).loginByAccountPwd(userAccToken);
		if (null == userDetails) {
			return null;
		}
		authenticationInfo = new SimpleAuthenticationInfo(
				userDetails,
				userDetails.getPassword(),
				ByteSource.Util.bytes(userDetails.getSalt()),
				getName()
		);
		return authenticationInfo;
	}


	@Override
	public boolean supports(AuthenticationToken token) {
		if (token instanceof UserAccToken) {
			return true;
		}
		return false;
	}

}
